#include <math.h>

#include "myComplex.h"

/* 复数构造 */
myComplex myComplex_Make(real rr, real ii)
{
    myComplex c;

    c.Re = rr;
    c.Im = ii;
    return c;
}

/* 复数加 */
myComplex *myComplex_Add(myComplex *ret, myComplex *a, myComplex *b)
{
    real rr, ii;

    rr = a->Re + b->Re;
    ii = a->Im + b->Im;

    ret->Re = rr;
    ret->Im = ii;
    return ret;
}

/* 复数减 */
myComplex *myComplex_Sub(myComplex *ret, myComplex *a, myComplex *b)
{
    real rr, ii;

    rr = a->Re - b->Re;
    ii = a->Im - b->Im;

    ret->Re = rr;
    ret->Im = ii;
    return ret;
}

/* 复数乘 */
myComplex *myComplex_Mul(myComplex *ret, myComplex *a, myComplex *b)
{
    /* a + bi  c + di  (ac - bd) + (bc + ad)i */
    real rr, ii;

    rr = a->Re * b->Re - a->Im * b->Im;
    ii = a->Re * b->Im + a->Im * b->Re;

    ret->Re = rr;
    ret->Im = ii;
    return ret;
}

/* 复数除 */
myComplex *myComplex_Div(myComplex *ret, myComplex *a, myComplex *b)
{
    /* a + bi  c + di  (ac + bd) / (c2 + d2) + ((bc - ad) / (c2 + d2))i */
    real rr, ii, div;

    div = b->Re * b->Re + b->Im * b->Im;
    rr = (a->Re * b->Re + a->Im * b->Im) / div;
    ii = (a->Im * b->Re - a->Re * b->Im) / div;

    ret->Re = rr;
    ret->Im = ii;
    return ret;
}

/* 复数模 */
real myComplex_Modulus(myComplex *c)
{
    return sqrt(c->Re * c->Re + c->Im * c->Im);
}
